package com.vincent.template.commons.validation.validators;

import com.vincent.template.commons.validation.constraints.MatchPath;
import org.apache.commons.lang3.StringUtils;

import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;

/**
 * @Author Vincent Wang
 * @Date 2020/10/21 19:36
 */
public class MatchPathValidator implements ConstraintValidator<MatchPath, String> {

    private boolean required;

    @Override
    public void initialize(MatchPath constraintAnnotation) {
        required = constraintAnnotation.required();
    }

    @Override
    public boolean isValid(String value, ConstraintValidatorContext constraintValidatorContext) {
        if (StringUtils.isBlank(value)) {
            return !required;
        }
        return value.startsWith("/") && value.length() > 1 && !value.contains("//");
    }
}
